package com.hyg.lib_common.ui.activity;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import android.Manifest;
import android.bluetooth.BluetoothA2dp;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothHeadset;
import android.bluetooth.BluetoothProfile;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.hyg.lib_base.lisener.PermissionListener;
import com.hyg.lib_base.mainUtils.BluetoothUtils;
import com.hyg.lib_base.mainUtils.StatusBarUtil;
import com.hyg.lib_common.Base.BaseActivity;
import com.hyg.lib_common.R;
import com.hyg.lib_common.constant.Constants;
import com.hyg.lib_common.databinding.ActivityBlueToothListBinding;
import com.hyg.lib_common.entity.BondDevicesModle;
import com.hyg.lib_common.ui.adpter.BlueToothConnectListAdapter;
import com.hyg.lib_common.ui.adpter.BlueToothUnconnectListAdapter;
import com.hyg.lib_common.ui.adpter.DividerDecoration;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;

@Route(path = Constants.PATH_ACTIVITY_MUSIC_BLUETOOTHLIST)
public class BlueToothListActivity extends BaseActivity {
    ActivityBlueToothListBinding binding;
    BluetoothUtils bluetoothUtils;
    ArrayList<BondDevicesModle> listConnected = new ArrayList<>();
    ArrayList<BluetoothDevice> listUnConnected = new ArrayList<>();
    BlueToothConnectListAdapter adapterConnected;
    BlueToothUnconnectListAdapter adapterUnConnected;
    BluetoothAdapter bluetoothAdapter;
    BluetoothHeadset mBluetoothHeadset;
    BluetoothA2dp mBluetoothA2dp;
    BluetoothDevice activeDevice;
    Animation rotate;
    String from = "0";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBlueToothListBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        StatusBarUtil.setStatusBar(1, this, getResources().getColor(R.color.white), 00, null, null, true);
        getBlueToothPermissin();
    }

    public void getBlueToothPermissin() {
        getPermissions(new String[]{Manifest.permission.BLUETOOTH,
                Manifest.permission.BLUETOOTH_ADMIN,
                Manifest.permission.ACCESS_COARSE_LOCATION,
                Manifest.permission.ACCESS_FINE_LOCATION,}, new PermissionListener() {
            @Override
            public void onResult(int[] results) {
                if (results[0] != 0) {
                    Toast.makeText(BlueToothListActivity.this, "音乐模块需要打开蓝牙设备权限", Toast.LENGTH_LONG).show();
                    finish();
                } else {
                    init();
//                    initBlueToothData();
//                    startRefresh();
                }
            }
        });
    }

    public void init() {
        initView();
        initBlueThoothView();
//        getBlueToothPermissin();
        initConnectedDevices();
        initUnConnectedDevices();
        initBlueToothStateListener();
    }

    public void initBlueThoothView() {
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        listUnConnected = new ArrayList<>();
        if (bluetoothAdapter == null) {
            Toast.makeText(this, "您的手机不支持蓝牙功能!", Toast.LENGTH_SHORT).show();
            return;
        }
        if (!bluetoothAdapter.isEnabled()) {
            Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(intent, 200);
        } else {
            bluetoothUtils = new BluetoothUtils(this);
            initBlueToothData();
            bluetoothAdapter.startDiscovery();
        }
    }


    public void initView() {
        binding.back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        binding.lnRefresh.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (bluetoothAdapter == null) {
                    Toast.makeText(BlueToothListActivity.this, "您的手机不支持蓝牙功能!", Toast.LENGTH_SHORT).show();
                    return;
                }
                if (!bluetoothAdapter.isEnabled()) {
                    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                    startActivityForResult(intent, 201);
                } else {
                    if (bluetoothAdapter.isDiscovering()) {
                        bluetoothAdapter.cancelDiscovery();
                    } else {
                        listUnConnected.clear();
                        Log.i("lgb", "onClick:result= " + bluetoothAdapter.startDiscovery());
                    }
                }
            }
        });
    }

    private void startProgressAnimation() {
        if (rotate != null) {
            binding.prRefrash.clearAnimation();
        }
        rotate = AnimationUtils.loadAnimation(BlueToothListActivity.this, R.anim.rotate_anim_repeat);
        binding.prRefrash.setAnimation(rotate);
        binding.prRefrash.startAnimation(rotate);
    }

    private void stopProgressAnimation() {
        binding.prRefrash.clearAnimation();
    }


    public void initBlueToothStateListener() {
        if (bluetoothUtils == null) {
            bluetoothUtils = new BluetoothUtils(this);
        }
        bluetoothUtils.setStateChangeListener(new BluetoothUtils.BluetootnStateChangeListener() {
            @Override
            public void onStart() {
                startProgressAnimation();
            }

            @Override
            public void onCancel() {
                binding.prRefrash.clearAnimation();
            }

            @Override
            public void onFinish() {
                binding.prRefrash.clearAnimation();
                if (bluetoothUtils != null) {
                    bluetoothUtils.onDestroy();
                }
                if (listUnConnected.size() == 0) {
                binding.tvDeviceAvailable.setText("可用设备(0)");
                }
            }

            @Override
            public void onProgress(BluetoothDevice device) {
                if (!listUnConnected.contains(device)
                        && BluetoothUtils.isMusicProduct(device)
                ) {
                    listUnConnected.add(device);
                    binding.tvDeviceAvailable.setText("可用设备("+listUnConnected.size()+")");

                }
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        adapterUnConnected.notifyDataSetChanged();
                    }
                });

            }

            @Override
            public void onConnecting(BluetoothDevice device) {
                startProgressAnimation();
            }

            @Override
            public void onBinding(BluetoothDevice device) {
                Log.i("lgb", "onBinding: ");
                binding.prRefrash.clearAnimation();
            }

            @Override
            public void onBindingCancel(BluetoothDevice device) {
                Log.i("lgb", "onBindingCancel: ");
                binding.prRefrash.clearAnimation();
            }

            @Override
            public void onConnected(BluetoothDevice device) {
                binding.prRefrash.clearAnimation();
                Log.i("lgb", "onConnected: ");
                initBlueToothData();
                listUnConnected.remove(device);
                adapterUnConnected.notifyDataSetChanged();
                if (getIntent().getStringExtra("type").equals("1")) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ToIntent(Constants.PATH_ACTIVITY_MODULE_HEALTH_MUSICBED, true);
                            overridePendingTransition(R.anim.fade, R.anim.hold);
                        }
                    }, 500);

                }
            }

            @Override
            public void onHeadsetActiveChanged(BluetoothDevice device) {

            }


            @Override
            public void onA2dpActiveChanged(BluetoothDevice device) {
                if (device == null) return;
                for (int i = 0; i < listConnected.size(); i++) {
                    if (device.getName().equalsIgnoreCase(listConnected.get(i).getDevice().getName())) {
                        listConnected.get(i).setState("使用中");
                    } else {
                        listConnected.get(i).setState("未使用");
                    }
                }
                if (adapterConnected != null) {
                    adapterConnected.notifyDataSetChanged();
                }
                if (BluetoothUtils.isMusicProduct(device)) {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            ToIntent(Constants.PATH_ACTIVITY_MODULE_HEALTH_MUSICBED, true);
                            overridePendingTransition(R.anim.fade, R.anim.hold);
                        }
                    }, 500);
                }
            }
        });
    }


    public void startRefresh() {
        listUnConnected.clear();
        if (bluetoothUtils != null) {
            bluetoothUtils.startSearchBluetoothDevice();
        } else {
            Log.i("lgb", "startRefresh: bluetoothUtils == null");
        }
    }


    public void initBlueToothData() {
        Log.i("lgb", "initBlueToothData: ");
        listConnected.clear();
        BluetoothAdapter.getDefaultAdapter().getProfileProxy(this, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                if (profile == BluetoothProfile.HEADSET) {
                    mBluetoothHeadset = (BluetoothHeadset) proxy;
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {

            }
        }, BluetoothProfile.HEADSET);


        BluetoothAdapter.getDefaultAdapter().getProfileProxy(this, new BluetoothProfile.ServiceListener() {
            @Override
            public void onServiceConnected(int profile, BluetoothProfile proxy) {
                if (proxy instanceof BluetoothA2dp) {
                    mBluetoothA2dp = (BluetoothA2dp) proxy;
                    try {
                        Class<?> bluetoothA2dp = Class.forName("android.bluetooth.BluetoothA2dp");
                        Method getActiveDevice = bluetoothA2dp.getMethod("getActiveDevice");
                        activeDevice = (BluetoothDevice) getActiveDevice.invoke(mBluetoothA2dp);
                        List<BluetoothDevice> mDevices = proxy.getConnectedDevices();
                        if (mDevices != null && mDevices.size() > 0) {
                            for (BluetoothDevice device : mDevices) {
                                if (activeDevice != null && device.getName().equalsIgnoreCase(activeDevice.getName())) {
                                    listConnected.add(new BondDevicesModle(device, "使用中", "yinyuezhen"));
                                } else {
                                    listConnected.add(new BondDevicesModle(device, "未使用", "yinyuezhen"));
                                }
                            }
                            binding.tvDeviceConnect.setText("配对过的设备("+listConnected.size()+")");
                            if (adapterConnected != null) {
                                adapterConnected.notifyDataSetChanged();
                            }
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                        Log.i("lgb", "onServiceConnected2222: Exception");
                    }
                }
            }

            @Override
            public void onServiceDisconnected(int profile) {
            }
        }, BluetoothProfile.A2DP);
    }


    public void initConnectedDevices() {
        listConnected = new ArrayList<>();
//      Set<BluetoothDevice> devices = bluetoothUtils.getpairedDevices();

        LinearLayoutManager layoutManager = new LinearLayoutManager(BlueToothListActivity.this);
        binding.rcvListConnected.setLayoutManager(layoutManager);
        adapterConnected = new BlueToothConnectListAdapter(this, listConnected);
        adapterConnected.setOnItemClickListener(new BlueToothConnectListAdapter.ListClickListener() {
            @Override
            public void onItemClicked(int position) {
                if (mBluetoothA2dp == null) return;
                try {
                    Class<?> bluetoothHeadset = Class.forName("android.bluetooth.BluetoothHeadset");
                    Method setActiveHeadsetDevice = bluetoothHeadset.getMethod("setActiveDevice", listConnected.get(position).getDevice().getClass());
                    setActiveHeadsetDevice.invoke(mBluetoothHeadset, listConnected.get(position).getDevice());

                    Class<?> bluetoothA2dp = Class.forName("android.bluetooth.BluetoothA2dp");
                    Method setActiveDevice = bluetoothA2dp.getMethod("setActiveDevice", listConnected.get(position).getDevice().getClass());
                    setActiveDevice.invoke(mBluetoothA2dp, listConnected.get(position).getDevice());

                } catch (Exception e) {
                    e.printStackTrace();
                    Log.i("lgb", "onServiceConnected1111: Exception");
                }
            }
        });
        binding.rcvListConnected.setAdapter(adapterConnected);
        DividerDecoration decoration1 = new DividerDecoration(1, dp2px(10), false);
        binding.rcvListConnected.addItemDecoration(decoration1);
    }

    public void initUnConnectedDevices() {
        listUnConnected = new ArrayList<>();
        LinearLayoutManager layoutManager = new LinearLayoutManager(BlueToothListActivity.this);
        binding.rcvListUnconnected.setLayoutManager(layoutManager);
        adapterUnConnected = new BlueToothUnconnectListAdapter(this, listUnConnected);
        adapterUnConnected.setOnItemClickListener(new BlueToothUnconnectListAdapter.ListClickListener() {
            @Override
            public void onItemClicked(int position) {
                Log.i("lgb", "onItemClicked1: ");
                bluetoothUtils.stopRefresh();
                if (listUnConnected.get(position).getBondState() == BluetoothDevice.BOND_BONDED) {
                    if (mBluetoothA2dp == null) {
                        return;
                    }
                    try {
                        //通过反射获取BluetoothA2dp中connect方法（hide的），进行连接。
                        Method connectMethod = BluetoothA2dp.class.getMethod("connect",
                                BluetoothDevice.class);
                        connectMethod.invoke(mBluetoothA2dp, listUnConnected.get(position));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else if (listUnConnected.get(position).getBondState() == BluetoothDevice.BOND_NONE) {
                    boolean result1 = listUnConnected.get(position).createBond();
                }
            }
        });
        binding.rcvListUnconnected.setAdapter(adapterUnConnected);
        DividerDecoration decoration = new DividerDecoration(1, dp2px(10), false);
        binding.rcvListUnconnected.addItemDecoration(decoration);
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 200 && resultCode == RESULT_OK) {
            bluetoothUtils = new BluetoothUtils(this);
            initBlueToothData();
            startRefresh();
        } else if (requestCode == 201 && resultCode == RESULT_OK) {
            startRefresh();
        } else if (requestCode == 200) {
            Toast.makeText(this, "听音乐功能需要您开启蓝牙!", Toast.LENGTH_SHORT).show();
        }
    }


    @Override
    public void finish() {
        super.finish();
        if (bluetoothUtils != null) {
            bluetoothUtils.onDestroy();
        }

    }
}